import { objectAny } from "../options/base";
import { showModal, showToast } from "./utils";
import QQMapWX from '../sdk/qqmap-wx-jssdk';

export async function openSetting(
	authouName : string
) {
	const confirm = await showModal({
		title: `授权提示`,
		showCancel: false,
		// content:'获取授权' + authouName + '失败,点击前往授权设置',
		content: `请开启位置信息授权，否者我们无法为您提供服务`
	});

	if (confirm) {
		uni.openSetting();
	}
}

export function getSetting() {
	return new Promise((resolve, reject) => {
		uni.getSetting({
			success: resolve,
			fail: reject
		})
	})
}

export function authorize(
	scope : `scope.userInfo` | `scope.userLocation` | `scope.userLocationBackground` | `scope.writePhotosAlbum`
) {
	return new Promise((resolve, reject) => {
		uni.authorize({
			scope,
			success: resolve,
			fail: () => {
				openSetting(`位置信息`);
				reject();
			}
		})
	})

}


export function getMyLocation() : Promise<{
	status : 1 | 2 | 3,
	results : objectAny
}> {
	return new Promise(async resolve => {
		try {
			// #ifdef MP-WEIXIN
			await authorize(`scope.userLocation`);
			// #endif

			uni.getLocation({
				type: 'wgs84',
				success: (res : objectAny) => {
					resolve({   //坐标获取成功
						status: 3,
						results: res
					})

				},
				fail: (err : objectAny) => {
					console.error(err)
					resolve({   //小程序已经授权但是坐标获取失败，可能是手机设置了关闭
						status: 2,
						results: {}
					})
				}
			});

		} catch (error) {
			console.error(error)
			resolve({       //小程序首次获取权限未通过,会自动打开设置页面
				status: 1,
				results: {}
			})
		}
	})
}

export function findShop() { //拿到商家的地理位置，用到了腾讯地图的api
	// 实例化API核心类
	var demo = new QQMapWX({
		key: 'QJOBZ-M2BWD-4A44K-PCYGC-GBEKF-GJFOQ' // 必填
	});
	// 调用接口
	demo.calculateDistance({
		to: [{
			latitude: 28.742305, //商家的纬度
			longitude: 105.227764, //商家的经度
		}],
		success: function (res : objectAny) {
			console.log(res)
			let hw = res.result.elements[0].distance //拿到距离(米)
			if (hw && hw !== -1) { //拿到正确的值
				//转换成公里
				hw = (hw / 2 / 500).toFixed(2) + '公里'
			} else {
				hw = "距离太近或请刷新重试"
			}
			console.log('腾讯地图计算距离商家' + hw);
		},
		fail: async (err : objectAny) => {
			console.log(`----calculateDistance--发生错误，错误如下：`)
			console.log(err)
			if (err.status === 1000) {
				await authorize(`scope.userLocation`);
			}
		}
	});
}